package lru;

import java.util.HashMap;
import java.util.Map;

/**
 * lru3
 * @author: luolidong
 * @create: 2021-07-18 11:28
 * @version: 1.0
 */
public class Lru3<K, V> {
    private class Node<K, V> {
        K k;
        V v;
        Node<K, V> next;
        Node<K, V> prev;

        public Node() {
        }

        public Node(K k, V v) {
            this.k = k;
            this.v = v;
        }
    }

    private class MyLruLinkedList<K, V> {
        Node<K, V> head;
        Node<K, V> tail;

        //初始化，头尾连接
        public MyLruLinkedList() {
            head = new Node<K, V>();
            tail = new Node<K, V>();
            head.next = tail;
            tail.prev = head;
        }

        //添加节点
        public void addNode(Node<K, V> node) {
            node.next = head.next;
            head.next.prev = node;
            head.next = node;
            node.prev = head;
        }

        //删除节点
        public void removeNode(Node<K, V> node) {
            node.next.prev = node.prev;
            node.prev.next = node.next;
            node.next = null;
            node.prev = null;
        }

        //获取尾结点
        public Node<K, V> getTailNode() {
            return tail.prev;
        }
    }

    private int capacity;
    private MyLruLinkedList<Integer, Integer> lruLinkedList;
    private Map<Integer, Node<Integer, Integer>> map;

    public Lru3(int capacity) {
        this.capacity = capacity;
        this.lruLinkedList = new MyLruLinkedList<>();
        this.map = new HashMap<>(capacity);
    }

    public int get(int key) {
        if (map.containsKey(key)) {
            //将该节点放到最前面
            //1.获取该节点
            Node<Integer, Integer> node = map.get(key);
            //2.删除该节点
            lruLinkedList.removeNode(node);
            //3.添加头
            lruLinkedList.addNode(node);
            return node.v;
        }
        return -1;
    }

    public void put(int key, int value) {
        //key已经存在，覆盖value,调整到头
        if (map.containsKey(key)) {
            Node<Integer, Integer> node = map.get(key);
            lruLinkedList.removeNode(node);
            node.v = value;
            lruLinkedList.addNode(node);
        } else {
            //如果key不存在，判断有没有满
            //满了，删除尾结点，在插入到头。
            if (map.size() == capacity) {
                Node<Integer, Integer> tailNode = lruLinkedList.getTailNode();
                lruLinkedList.removeNode(tailNode);
                map.remove(tailNode.k);//注意这里是map删除尾结点的key
            }
            Node<Integer, Integer> newNode = new Node<>(key, value);
            map.put(key, newNode);
            //容量没有满
            lruLinkedList.addNode(newNode);
        }
    }
}
